/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { error } from 'cc';
import { conflict } from './base';

const TAG = 'lcc/core/pipeline.ts';

/**
 * @zh
 * 管道函数
 */
export type PipelineFunction = (input: any) => Promise<any>;

/**
 * @zh
 * 处理管道<br/>
 * 用于对输入数据的链式处理
 */
class Pipeline {
    /**
     * @zh
     * 静态对象
     */
    private static _instance: Pipeline = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (Pipeline._instance === null) {
            Pipeline._instance = new Pipeline();
        }
        return Pipeline._instance;
    }

    /**
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 管道映射表
     */
    private _pipelineMap: { [key: string]: PipelineFunction } = Object.create(null);

    /**
     * @zh
     * 注册管道
     *
     * @param name 管道名称
     * @param pipeline 管道函数
     * @param override 是否覆盖
     */
    register(name: string, pipeline: PipelineFunction, override = false) {
        if (!override && this._pipelineMap[name]) {
            conflict(TAG, `pipeline ${name} conflict`);
        }
        this._pipelineMap[name] = pipeline;
    }

    /**
     * @zh
     * 管道处理
     *
     * @param input 输入数据
     * @param pipelines 管道列表
     *
     * @returns 处理后的数据
     */
    async handle<T = any>(input: any, pipelines: string[]) {
        let result = input;
        for (let name of pipelines) {
            let pipeline = this._pipelineMap[name];
            if (!pipeline) {
                error(TAG, `pipeline ${name} not found!`);
                return null;
            }
            result = await pipeline(result);
        }
        return result as T;
    }
}

/**
 * @zh
 * 处理管道对象
 */
export const pipeline = Pipeline.instance;
